package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.HealthRecordsAdapter;
import com.xn.app.muying.bean.HealthRecordsListBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 健康档案
 * Created by Administrator on 2017/4/14.
 */
public class HealthRecordsActivity extends BaseActivity implements View.OnClickListener {
    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    private ImageView img_right = null;
    private ListView lv;
    private HealthRecordsAdapter healthRecordsAdapter;
    //数据库
    private DBManager db = null;
    //加载框
    AlertDialog dialog;
    private TextView name, age, sex, yunzhou;
    //无数据页面
    private LinearLayout nodata;
    //用户信息页面
    private LinearLayout data_linearlayout;
    private String jzrqsj;
    //就诊人就诊信息
    private ArrayList<HealthRecordsListBean> list = null;
    private TextView tishi;
    private String identityId, fullname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_healthrecords);
        db = new DBManager(this);
        if (NetworkUtil.isNetworkAvailable(this)) {
            initView();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    private void initView() {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "健康档案");
        } catch (Exception e) {
            e.printStackTrace();
        }
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_right = (ImageView) findViewById(R.id.img_right);
        lv = (ListView) findViewById(R.id.healthrecords_listview);
        nodata = (LinearLayout) findViewById(R.id.nodata_linearlayout);
        name = (TextView) findViewById(R.id.name);
        age = (TextView) findViewById(R.id.age);
        sex = (TextView) findViewById(R.id.sex);
        yunzhou = (TextView) findViewById(R.id.yunzhou);
        data_linearlayout = (LinearLayout) findViewById(R.id.data_linearlayout);
        tishi = (TextView) findViewById(R.id.healthrecords_tishi);
        title_name.setText("健康档案");
        img_right.setVisibility(View.VISIBLE);
        img_right.setImageResource(R.mipmap.history_img);
        img_back.setOnClickListener(this);
        img_right.setOnClickListener(this);
        healthRecordsAdapter = new HealthRecordsAdapter(this);
        lv.setAdapter(healthRecordsAdapter);
        //数据下载
        VisitInfoLoading();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list != null) {
                    Intent intent = new Intent();
                    intent.putExtra("registerID", list.get(position).getRegisterID());
                    intent.setClass(HealthRecordsActivity.this, HealthRecordsCategoryActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    //下载检查数据
    private void VisitReportLoading(final String id, final String name) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.VisitReport(id, name)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler2.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler2.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            //显示用户数据
            data_linearlayout.setVisibility(LinearLayout.VISIBLE);
            switch (msg.what) {
                case 0:
                    onJsonVisitReportData(msg.obj.toString());
                    break;
                case 1:
                    if (lv.getVisibility() == View.VISIBLE) {
                        lv.setVisibility(MyListView.GONE);
                    }
                    if (nodata.getVisibility() == View.GONE) {
                        nodata.setVisibility(MyListView.VISIBLE);
                    }

                    break;
            }
        }
    };

    //列表数据整理
    private void onJsonVisitReportData(String s) {
        try {
            //一天的时间戳  86400为一天的时间戳
            long oneDay = AppConstant.oneDay;
            //解析数据
            JSONObject jsonObject = new JSONObject(s);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String id = object.optString("id");
                jzrqsj = object.optString("jzrqsj");
                String jzksmc = object.optString("jzksmc");
                String zrys = object.optString("zrys");
                String zryszc = object.optString("zryszc");
                String hospital = object.optString("hospital");
                String registerID = object.optString("registerID");
                HealthRecordsListBean healthRecordsListBean = new HealthRecordsListBean();
                healthRecordsListBean.setId(id);
                healthRecordsListBean.setJzrqsj(jzrqsj);
                healthRecordsListBean.setJzksmc(jzksmc);
                healthRecordsListBean.setZrys(zrys);
                healthRecordsListBean.setZryszc(zryszc);
                healthRecordsListBean.setHospital(hospital);
                healthRecordsListBean.setRegisterID(registerID);
                if (jzrqsj != null && DateUtils.getNumberDate() - DateUtils.getStringToDate(jzrqsj.replace("T", " ")) <= oneDay * 30) {
                    list.add(healthRecordsListBean);
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (list != null && list.size() > 0) {
                        nodata.setVisibility(View.GONE);
                        lv.setVisibility(View.VISIBLE);
                        tishi.setVisibility(View.VISIBLE);
                    } else {
                        nodata.setVisibility(View.VISIBLE);
                        lv.setVisibility(View.GONE);
                        tishi.setVisibility(View.GONE);
                    }
                }
            });
            healthRecordsAdapter.getData(list);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //下载用户数据
    private void VisitInfoLoading() {
        dialog = new MyAlertDialog().ShowDialog(HealthRecordsActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.VisitInfo(db.select("identityId"))).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    onJsonData(msg.obj.toString());
                    break;
                case 1:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (lv.getVisibility() == View.VISIBLE) {
                        lv.setVisibility(MyListView.GONE);
                    }
                    if (nodata.getVisibility() == View.GONE) {
                        nodata.setVisibility(MyListView.VISIBLE);
                    }

                    break;
            }
        }
    };

    //解析数据
    private void onJsonData(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            fullname = jsonObject.optString("fullname");
            final String gender = jsonObject.optString("gender");
            final String birthday = jsonObject.optString("age");
            identityId = jsonObject.optString("identityId");
            final String pergnancyWeek = jsonObject.optString("pergnancyWeek");
            final String remainderDay = jsonObject.optString("remainderDay");
            if (identityId != null && fullname != null) {
                VisitReportLoading(identityId, fullname);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        name.setText(fullname);
                        age.setText(birthday + "岁");
                        sex.setText(gender);
                        if (gender.equals("女")) {
                            if (pergnancyWeek.equals("0") && remainderDay.equals("0")) {
                                yunzhou.setVisibility(View.GONE);
                            } else {
                                yunzhou.setText("孕周：" + pergnancyWeek + "周+" + remainderDay + "天");
                            }
                        } else {
                            yunzhou.setVisibility(View.GONE);
                        }
                    }
                });
            } else {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_right:
                Intent intent = new Intent();
                intent.putExtra("fullname", fullname);
                intent.putExtra("identityId", identityId);
                intent.setClass(HealthRecordsActivity.this, HealthRecordsHistoryActivity.class);
                startActivity(intent);
                break;
        }
    }

}
